package secret

import (
	"encoding/base64"

	"github.com/infraboard/mcube/crypto/cbc"
	"github.com/rs/xid"
)

func NewSecret(req *CreateSecretRequest) *Secret {
	return &Secret{
		Id:   xid.New().String(),
		Spec: req,
	}
}

// 加密, 对称加密: key,
func (s *Secret) Encrypt(key string) error {
	if s.Spec.Value == "" {
		return nil
	}

	cipherData, err := cbc.Encrypt([]byte(s.Spec.Value), []byte(key))
	if err != nil {
		return err
	}

	// bytes 使用base64 编码
	s.Spec.Value = base64.StdEncoding.EncodeToString(cipherData)
	return nil
}

// 解密, 对称加密: key
func (s *Secret) Decrypt(key string) error {
	// base64解码
	cipherData, err := base64.StdEncoding.DecodeString(s.Spec.Value)
	if err != nil {
		return err
	}
	planData, err := cbc.Decrypt(cipherData, []byte(key))
	if err != nil {
		return err
	}
	s.Spec.Value = string(planData)
	return nil
}

func (s *Secret) Desense() {
	s.Spec.Value = s.Spec.Value[:4] + "*****"
}
